package com.netease.nie.base.jdbc;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import com.netease.nie.base.utils.HashUtils;

/**
 * 
 * @author KingsHunter
 * @createDate August 31st,2016
 *
 */
public class DBDao extends AbstractJdbcDao {

	protected void statementBatchInsert(List<String> sqlList) {
		if (!sqlList.isEmpty()) {
			Connection connection = getConnection(false);
			int sqlListSize = sqlList.size();
			String sql = null;
			Statement statement = null;
			int count = 0;
			try {
				statement = connection.createStatement();
				for (int i = 0; i < sqlListSize; i++) {
					if (count > 0 && count % 1000 == 0) {
						statement.executeBatch();
						statement.clearBatch();				
					}
					sql = sqlList.get(i);
					statement.addBatch(sql);
					count++;
				}
				statement.executeBatch();
				connection.commit();
			} catch (SQLException e) {
				rollback(connection);
			} finally {
				close(statement);
				close(connection);
			}
		}
	}
	
	public String getTableIndex(Integer hashType, String hashConfig, Object value) {
		String tableIndex = null;
		switch (hashType) {
		case 1: {			
			//SAME type
			tableIndex = value.toString().substring(1, 3);
		}
		break;
		
		case 2 : {
			//HASH type
			int hashCode = Integer.valueOf(hashConfig);
			Long hashTemp = Long.valueOf(value.toString()) % hashCode;
			Integer hash = hashTemp == 0 ? hashCode : hashTemp.intValue();
			tableIndex = generateTableIndex(hashConfig, String.valueOf(hash));
		}
		break;

		case 3 : {
			//STRHASH type
			Long bkdrHash = (long) HashUtils.bkdrHash(value.toString());
			int hashCode = Integer.valueOf(hashConfig);
			Long hashTemp = bkdrHash % hashCode;
			Integer hash = hashTemp == 0 ? hashCode : hashTemp.intValue();
			tableIndex = generateTableIndex(hashConfig, String.valueOf(hash));
		}
		break;
		default:
			break;
		}
		return tableIndex;
	}
	
	private String generateTableIndex(String hashConfig, String hashResult) {
		int hashConfigLen = hashConfig.length();
		int hashResultLen = hashResult.length();
		int diff = hashConfigLen - hashResultLen;
		String tableIndex = "";
		if (diff == 0)
			return hashResult;
		for (int i = 0; i < diff; i++) {
			tableIndex += "0";
		}
		tableIndex += hashResult;
		return tableIndex;
	}
}
